<template>
  <div class="content">
    <div class="header-container">
      <h1>我的收货地址</h1>
      <TabItem
        :tabs="tabs"
        :active-index="activeIndex"
        @handleClick="handleClick"
      />
    </div>
    <div class="middle-container">
      <div class="add-address" @click="addAddress" v-text="activeIndex === 0 ? '新增收货地址' : '新增推单地址'">
        新增收货地址
      </div>
      <div class="create-address">
        您已经创建<span v-text="total" />个收货地址，最多可创建<span>20</span>个
      </div>
    </div>
    <!-- 动态生成地址清单列表 切换不同tab发起请求-->
    <div v-for="(item,index) in list" :key="index" class="main-container">
      <img src="../../assets/images/no-default.png" alt="">
      <div class="user-info">
        <div class="info-defaul">
          <span>收货人信息</span>
        </div>
        <div><span>收货人姓名：</span><span v-text="item.receiverName">张生</span></div>
        <div><span>手机号码：</span><span v-text="item.receiverPhone">13265034452</span></div>
        <div class="address-container">
          <div class="left">
            <span>收货地址：</span><span v-text="formatAddress(item)">广东 广州 东山区 宽城区凯旋路3050</span>
          </div>
          <div class="right">
            <span class="edit-address" @click="editAddress(item)">编辑</span>
            <el-button
              type="text"
              class="del-btn"
              @click="deleteAddress(item)"
            >删除</el-button>
          </div>
        </div>
      </div>
      <span class="el-icon-close" @click="deleteAddress(item)" />
    </div>
    <!-- 分页 -->

    <el-pagination
      background
      :current-page.sync="pageParams.index"
      layout="prev, pager, next"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="pageParams.size"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 弹框新增/编辑收货地址 -->
    <div v-if="showPopUp" class="pop-up">
      <div class="add-container">
        <div class="txt">
          <div>{{ popTitle }}</div>
          <span class="el-icon-close" @click="closePopUp" />
        </div>

        <div class="add-content">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="收货地址" prop="addressTitle">
              <el-input
                v-model="ruleForm.addressTitle"
                prefix-icon="el-icon-add-location"
                placeholder="点击选择收货地址"
                @click.native="chooseAddress"
                @focus="hideErrMsg('addressTitle')"
              />
            </el-form-item>
            <el-form-item label="详细地址" prop="receiveAddress">
              <el-input
                v-model="ruleForm.receiveAddress"
                type="textarea"
                maxlength="50"
                placeholder="街道，楼牌号等"
                @focus="hideErrMsg('receiveAddress')"
              />
              <span class="num" v-text="ruleForm.receiveAddress.length + '/50'">0/50</span>
            </el-form-item>
            <el-form-item label="收货人姓名" prop="receiverName">
              <el-input
                v-model="ruleForm.receiverName"
                @focus="hideErrMsg('receiverName')"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="receiverPhone">
              <el-input v-model="ruleForm.receiverPhone" @focus="hideErrMsg('receiverPhone')" />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="save"
                @click="save"
              >保存</el-button>
              <el-button
                class="cancel"
                @click="closePopUp('ruleForm')"
              >取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 选择地址弹窗 -->
    <ChooseMap v-if="showMap" ref="addressMap" :location="{lat: ruleForm.latitude, lng: ruleForm.longitude}" @concel="concel" @submitMap="submitMap" />
  </div>
</template>

<script>
  import { MessageBox } from 'element-ui'
import TabItem from '../../components/Tab'
import ChooseMap from '@/components/ChooseMap'
import { addAddress, listAddress, getAddressInfo, modifyAddress, deleteAddress } from '@/api/address'
export default {
  components: {
    TabItem,
    ChooseMap
  },
  data() {
    return {
      tabs: ['下单收货地址', '推单收货地址'],
      activeIndex: 0,
      showPopUp: false,
      showMap: false,
      popTitle: '',
      ruleForm: {
        id: '',
        addressTitle: '',
        receiveAddress: '',
        receiveProvince: '',
        receiveCity: '',
        receiveDistrict: '',
        latitude: '',
        longitude: '',
        receiverName: '',
        receiverPhone: ''
      },
      rules: {
        addressTitle: [
          { required: true, message: '请选择收货地址', trigger: 'change' }
        ],
        receiveAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
          {
            pattern: /^[\S\n\s]{1,50}$/,
            message: '地址不能大于50字',
            trigger: 'blur'
          }
        ],
        receiverName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' },
          {
            pattern: /\S/,
            message: '收货人姓名格式不正确',
            trigger: 'blur'
          }
        ],
        receiverPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur'
          }
        ]
      },
      // 分页参数
      pageParams: {
        index: 1,
        size: 5
      },
      total: 0,
      list: [],
      companyFlag: false
    }
  },
  watch: {
    activeIndex() {
      this.pageParams.index = 1
      this.list = []
      this.total = 0
      this.companyFlag = false
      this.getList()
    }
  },
  mounted() {
    this.handleClick(this.activeIndex)
  },
  created() {
    this.getList()
  },
  methods: {
    chooseAddress() {
      document.body.style.overflow = 'hidden'
      this.showMap = true
    },
    getList() {
      let type = 'address'
      if (this.activeIndex === 1) {
        type = 'push'
      }
      listAddress(this.pageParams, type).then(response => {
        if (response.data) {
          this.list = response.data.records
          this.total = response.data.total
        } else {
          this.$message.error(response.message)
          if (response.code === 11) {
            this.companyFlag = true
          }
        }
      })
    },
    concel() {
      this.showMap = false
    },
    submitMap(val) {
      this.showMap = false
      this.ruleForm.addressTitle = val.receiveProvince + val.receiveCity + val.receiveDistrict + val.receiveAddress
      this.ruleForm.receiveAddress = val.receiveAddress
      this.ruleForm.receiveProvince = val.receiveProvince
      this.ruleForm.receiveCity = val.receiveCity
      this.ruleForm.receiveDistrict = val.receiveDistrict
      this.ruleForm.latitude = val.latitude
      this.ruleForm.longitude = val.longitude
    },
    // 页个数数改变的时候可获取当前显示个数
    handleSizeChange(size) {
      this.pageParams.size = size
      // this.loadPost();个数改变的时候再次调用请求
    },
    // 页数改变的时候可获取当前显示当前页码数
    handleCurrentChange(currentPage) {
      this.pageParams.index = currentPage
      this.getList()
    },
    // 删除地址
    deleteAddress(item) {
      MessageBox.confirm('您确定要删除该地址么', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          let type = ''
          if (this.activeIndex === 1) {
            type = 'push-edit'
          }
          deleteAddress(item.id, type).then(response => {
            if (response.data) {
              // 当前页的数据项被删除完了
              if (this.list.length - 1 === 0) {
                const { index, size } = this.pageParams
                // 最大页码
                const page = Math.ceil(this.total / size)
                // 第一页
                if (index === 1 && index === page) {
                  this.total = 0
                  this.list = []
                } else {
                  if (index === page) { // 最后一页
                    this.pageParams.index--
                  }
                  this.getList()
                }
              } else {
                this.getList()
              }
              this.$message.success('删除成功!')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleClick(index) {
      console.log(typeof index)
      this.activeIndex = index
      // 发起请求
    },
    // 新增地址
    addAddress() {
      if (this.total >= 20) {
        this.$message.error('已达到20条上限地址，请先删除不常用地址')
        return
      }
      if (this.companyFlag) {
        this.$message.error('企业账号无法新增推单地址')
        return
      }
      if (this.activeIndex === 0) {
        this.popTitle = '新增收货地址'
      } else {
        this.popTitle = '新增推单地址'
      }
      document.body.style.overflow = 'hidden'
      this.showPopUp = true
      Object.assign(this.$data.ruleForm, this.$options.data().ruleForm)
    },
    // 修改地址
    editAddress(item) {
      let type = 'address-edit'
      if (this.activeIndex === 0) {
        this.popTitle = '编辑收货地址'
      } else {
        this.popTitle = '编辑推单地址'
        type = 'push-edit'
      }
      document.body.style.overflow = 'hidden'
      getAddressInfo(item.id, type).then(response => {
        this.ruleForm = response.data
        this.ruleForm.addressTitle = response.data.receiveProvince + response.data.receiveCity + response.data.receiveDistrict + response.data.receiveAddress
      })
      this.showPopUp = true
    },
    // 关闭新增、修改弹窗
    closePopUp() {
      this.showPopUp = false
      document.body.style.overflow = 'auto'
      Object.assign(this.$data.ruleForm, this.$options.data().ruleForm)
    },
    // 保存地址
    save() {
      if (this.total >= 20) {
        this.$message.error('已达到20条上限地址，请先删除不常用地址')
        return
      }
      if (this.companyFlag) {
        this.$message.error('企业账号无法新增推单地址')
        return
      }
      this.$refs.ruleForm.validate(isValid => {
        if (isValid) {
          if (!this.ruleForm.id) {
            // 新增地址
            let type = 'address-add'
            if (this.activeIndex === 1) {
              type = 'push-add'
            }
            addAddress(this.ruleForm, type).then(response => {
              if (response.data) {
                this.$message.success('新增成功')
                this.closePopUp()
                this.getList()
              }
            })
          } else {
            // 修改地址
            let type = ''
            if (this.activeIndex === 1) {
              type = 'push-edit'
            }
            modifyAddress(this.ruleForm, type).then(response => {
              if (response.data) {
                this.$message.success('修改成功!')
                this.closePopUp()
                this.getList()
              } else {
                this.$message.error(response.message)
              }
            }).catch(() => {
              this.$message.error('系统繁忙，请稍后重试！')
            })
          }
        }
      })
    },
    // 格式化地址
    formatAddress(item) {
      return `${item.receiveProvince} ${item.receiveCity} ${item.receiveDistrict} ${item.receiveAddress}`
    },
    // 重置
    resetForm() {
      this.showPopUp = false
    },
    // 移除错误提示
    hideErrMsg(progName) {
      this.$refs['ruleForm'].clearValidate(progName)
    }
  }
}
</script>

<style scoped lang="scss">
.el-pagination{
  height: 130px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #fff;
    color: #FF3B30FF;
    border: 1px solid #FF3B30FF;
}

::v-deep .el-pagination.is-background .el-pager li:not(.disabled){
// background-color: #fff;
border: 1px solid #DDDDDDFF;
}
::v-deep .el-pagination.is-background .btn-prev{
border: 1px solid #DDDDDDFF;
padding: 0 15px;
}
::v-deep .el-icon-arrow-left:before {
    content: "上一页";
}
::v-deep .el-pagination.is-background .btn-next{
border: 1px solid #DDDDDDFF;
padding: 0 15px;
}
::v-deep .el-icon-arrow-right:before {
    content: "下一页";
}
// 、、、、、、、、、、
.content {
  background-color: #f7f7f7 !important;
  height: 100%;
  .save {
    width: 110px;
    height: 37px;
    background-color: #ff3b30;
    border: none;
  }
  .cancel {
    width: 110px;
    height: 37px;
    background-color: #f5f5f5;
  }
  .pop-up {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    .add-container {
      width: 713px;
      .txt {
        color: #3d3d3d;
        font-size: 16px;
        border: 1px solid #e5e5e5;
        height: 42px;
        background-color: #e5e5e5;
        display: flex;
        padding: 0 15px 0 21px;
        justify-content: space-between;
        align-items: center;
        .el-icon-close {
          font-weight: 700;
        }
        .el-icon-close:hover {
          cursor: pointer;
        }
      }
      .add-content {
        background-color: #fff;
        height: 400px;
        width: 100%;
        padding: 20px 0 0 94px;
      }
    }
  }
  ::v-deep .el-input__inner {
    height: 35px;
    font-size: 13px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 20px;
    height: 35px;
  }
  ::v-deep .el-form-item:nth-child(2) {
    height: 89px;
    margin-bottom: 0;
    position: relative;
    .el-form-item__error {
      top: 201%;
    }
    .num {
      font-size: 12px;
      color: #6b6b6b;
      position: absolute;
      bottom: -50px;
      left: 250px;
    }
  }
  ::v-deep .el-form-item__content {
    height: 35px;
  }
  ::v-deep .el-input {
    height: 35px;
    width: 236px;
  }
  ::v-deep .el-form-item__label {
    height: 35px;
  }
  ::v-deep .el-textarea__inner {
    width: 236px;
    height: 70px;
    font-size: 13px;
    //  margin-bottom: 19px;
  }
  ::v-deep .el-textarea {
    width: 236px;
  }
  ::v-deep .el-input__icon {
    color: #ff3b30;
  }
}

.header-container {
  height: 57px;
  background-color: #fff;
  padding: 18px 20px 18px 30px;
  display: flex;

  align-items: center;
  margin-bottom: 20px;
  h1 {
    font-weight: 700;
    font-size: 16px;
  }
}
.middle-container {
  padding-bottom: 2px;
  background-color: #f7f7f7;
  display: flex;
  align-items: center;

  .add-address {
    width: 148px;
    height: 32px;
    border-radius: 4px;
    background-color: #fff4f3ff;
    color: #ff3b30ff;
    border: 1px solid #ff3b30ff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
  }
  .add-address:hover {
    cursor: pointer;
  }
  .create-address {
    color: #8e8e93ff;
    font-size: 12px;
    span {
      color: #fc8a41;
    }
  }
}
.main-container {
  width: 1032px;
  height: 160px;

  background: url("../../assets/images/address-img.png");
  background-repeat: no-repeat;

  background-color: #f7f7f7;
  background-position: 0% 0%;
  background-size: cover;
  position: relative;
  display: flex;
  margin-top: 20px;
  .el-icon-close {
    color: #a7a7aaff;
    font-size: 8px;
    position: absolute;
    top: 10px;
    right: 15px;
  }
  img {
    width: 4px;
    height: 152px;
    margin-right: 37px;
  }
  .user-info {
      width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    //  align-items: center;
    justify-content: space-around;
    color: #8e8e93ff;
    .address-container {
      width: 100%;
      display: flex;
    justify-content: space-between!important;
    align-items: center;
     padding-right: 50px;
    .left{
      flex: 1;
    }
      .right {
        width: 74px;
         display: flex;
    justify-content: center;
    align-items: center;
        color: #c7c7ccff;
        margin-right: 0;
        span:hover {
          cursor: pointer;
        }
        .del-btn {
          margin-left: 16px;
          color: #8e8e93ff;
        }
      }
    }
    .info-defaul {
      display: flex;
      .defaul {
        padding: 0 4px;
        background-color: #fc8a41;
        border-radius: 10px;
        color: #fff;
        text-align: center;
        margin-left: 11px;
      }
    }
  }
}
</style>
<style lang="scss">
.main-container .user-info .address-container .right .del-btn[data-v-b750f9b6] {
  color: #c7c7ccff;
}
.el-message-box {
  width: 538px;
  height: 255px;
}
.el-message-box--center .el-message-box__header {
  padding: 0;
  width: 100%;
}
.el-message-box__title {
  height: 45px;
  display: flex;
  background-color: #f5f5f5;
  justify-content: start !important;
  border-bottom: 1px solid #e5e5e5ff;
  align-items: center;
  .el-message-box__status {
    display: none;
    font-size: 16px;
  }
  span {
    margin-left: 15px;
  }
}
.el-message-box__content {
  padding: 0;
  margin: 48px 0;
  .el-message-box__container {
    .el-message-box__message {
      p:before {
        width: 0;
        height: 0;
        border-top: solid 10px transparent;
        border-right: solid 15px #fc8a41;
        border-bottom: solid 10px transparent;
        //   background-color: #FF3B30;
        transform: rotate(90deg);
        position: absolute;
        top: 1px;
        left: 31%;
        content: "";
      }
      p:after {
        width: 0;
        height: 0;
        content: "!";
        position: absolute;
        font-size: 10px;
        top: -1px;
        left: 32%;
        color: #fff;
      }
    }
  }
}
.el-message-box__btns {
  padding: 0;
  ::v-deep .el-message-box__btns .el-button {
    line-height: 37px;
  }
  .el-button {
    width: 110px;
    height: 37px;
    border-radius: 4px;
    text-align: center;
    background: #ff3b30;
    color: #fff;
    font-size: 12px;
  }
  .el-button--primary {
    background-color: #f5f5f5;
    color: #838383;
    border-color: #838383;
  }
  .el-message-box__btns button:nth-child(2) {
    margin-left: 16px;
  }
}
</style>
